package NIO_AIO_Netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * @program: planet-company
 * @description:
 * @author: jyz
 * @create: 2019-09-21 17:44
 **/
public class NettyServerTest {


    class NettyServer{
        int port = 8888;
        public NettyServer(int port){
            this.port = port;
        }

        public void serverStart(){
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workGroup = new NioEventLoopGroup();

            //对Netty进行配置
            ServerBootstrap server = new ServerBootstrap();
            //指定线程组：第一个线程组负责连接，第二个线程组服务work
            server.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)//设置什么通道，这里我们用的是NIO的通道
                    .childHandler(new ChannelInitializer<SocketChannel>() {//是当有客户端连上来了，我会给他一个监听器，让它进行处理
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //这个监听器是怎么处理的，就是在这个通道上加一个对这个通道的处理器
                    //也就是说只要这个通道初始化了，我就是这个通道上添加一个这个通道的处理器
                    socketChannel.pipeline().addLast(new Handler());
                }
            });


            try {
                ChannelFuture f = server.bind(port).sync();
                f.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                bossGroup.shutdownGracefully();
                workGroup.shutdownGracefully();
            }
        }
    }

    /**
     * 自定义一个处理器，，，注册在相关的通道上
     */
    class Handler extends ChannelInboundHandlerAdapter{

        //就是当数据已经读过来的时候，你要怎么做，怎么写回去
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            super.channelRead(ctx, msg);
            System.out.println("server: channel read");
            ByteBuf byteBuf = (ByteBuf)msg;

            System.out.println(byteBuf.toString(CharsetUtil.UTF_8));

            ctx.writeAndFlush(msg);
            ctx.close();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
            cause.printStackTrace();
            ctx.close();
        }
    }
}
